
package com.wanxi.education.util;

import io.netty.handler.codec.EncoderException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: 寇文宝
 * @Description: 通过视频链接url抓取视频时长
 * @Date: Created in 2021/9/25
 * @Version: 1.0
 */
public class VideoUtils {

    public static String getDuration(String url) throws IOException, EncoderException {
        //ffmpeg命令位置
        String ffmpeg_path="D:\\ffmpeg\\ffmpeg.exe";

        //拼接系统命令
        List<String> commands = new java.util.ArrayList<String>();
        commands.add(ffmpeg_path);
        commands.add("-i");
        commands.add(url);

        //执行系统命令
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(commands);
        final Process p = builder.start();
        //从输入流中读取视频信息
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();

        //从视频信息中解析时长
        String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
        Pattern pattern = Pattern.compile(regexDuration);
        Matcher m = pattern.matcher(sb.toString());
        if (m.find()) {
            System.out.println("视频时长："+m.group(1));
            return m.group(1);
        }
        return "00:00:00";
    }
}
